package com.cdtu.store.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cdtu.store.auth.entity.UserInfo;
import com.cdtu.store.common.entity.PageResult;
import com.cdtu.store.common.utils.IdWorker;
import com.cdtu.store.order.dao.OrderDao;
import com.cdtu.store.order.dao.OrderDetailDao;
import com.cdtu.store.order.dao.OrderStatusDao;
import com.cdtu.store.order.entity.Order;
import com.cdtu.store.order.entity.OrderDetail;
import com.cdtu.store.order.entity.OrderStatus;
import com.cdtu.store.order.interceptor.LoginInterceptor;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderDetailDao orderDetailDao;

    @Autowired
    private OrderStatusDao orderStatusDao;


    @Transactional
    public Long createOrder(Order order) {
        // 生成orderId
        long orderId = idWorker.nextId();
        // 获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        // 初始化数据
        order.setBuyerNick(user.getUsername());
        order.setBuyerRate(false);
        order.setCreateTime(new Date());
        order.setOrderId(orderId);
        order.setUserId(user.getId());
        // 保存数据
        this.orderDao.insert(order);

        // 保存订单状态
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        orderStatus.setCreateTime(order.getCreateTime());
        // 初始状态为未付款
        orderStatus.setStatus(1);

        this.orderStatusDao.insert(orderStatus);

        // 订单详情中添加orderId
        order.getOrderDetails().forEach(od -> od.setOrderId(orderId));
        // 保存订单详情,使用批量插入功能
        order.getOrderDetails().forEach(orderDetail->{
            this.orderDetailDao.insert(orderDetail);
        });

        log.debug("生成订单，订单编号：{}，用户id：{}", orderId, user.getId());

        return orderId;
    }

    public Order queryById(Long id) {
        // 查询订单
        Order order = this.orderDao.selectById(id);

        // 查询订单详情
        List<OrderDetail> details = this.orderDetailDao.selectList(new QueryWrapper<OrderDetail>().eq("order_id",id));
        order.setOrderDetails(details);

        // 查询订单状态
        OrderStatus status = this.orderStatusDao.selectById(order.getOrderId());
        order.setStatus(status.getStatus());
        return order;
    }

    public PageResult<Order> queryUserOrderList(Integer page, Integer rows, Integer status) {
        try {
            // 分页
            PageHelper.startPage(page, rows);
            // 获取登录用户
            UserInfo user = LoginInterceptor.getLoginUser();
            // 创建查询条件
            Page<Order> pageInfo = (Page<Order>) this.orderDao.queryOrderList(user.getId(), status);
            return new PageResult<>(pageInfo.getTotal(), pageInfo);
        } catch (Exception e) {
            log.error("查询订单出错", e);
            return null;
        }
    }

    @Transactional
    public Boolean updateStatus(Long id, Integer status) {
        OrderStatus record = new OrderStatus();
        record.setOrderId(id);
        record.setStatus(status);
        // 根据状态判断要修改的时间
        switch (status) {
            case 2:
                //付款
                record.setPaymentTime(new Date());
                break;
            case 3:
                // 发货
                record.setConsignTime(new Date());
                break;
            case 4:
                // 确认收获，订单结束
                record.setEndTime(new Date());
                break;
            case 5:
                // 交易失败，订单关闭
                record.setCloseTime(new Date());
                break;
            case 6:
                // 评价时间
                record.setCommentTime(new Date());
                break;
            default:
                return null;
        }
        int count = this.orderStatusDao.update(record,new UpdateWrapper<OrderStatus>().eq("order_id",id));
        return count == 1;
    }

    public List<Order> queryAddrs() {
        // 获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        List<Order> orders = this.orderDao.selectList(new QueryWrapper<Order>().eq("user_id", user.getId()));
        return orders;
    }
}
